package com.ykzhujiang.lovespirit.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;

import com.ykzhujiang.lovespirit.entity.LThread;
import com.ykzhujiang.lovespirit.entity.Notice;
import com.ykzhujiang.lovespirit.parser.html.HTMLParser;

public class Utility {
	public static HashMap months;

	public static int GetMonth(String month) {
		if (months == null) {
			months = new HashMap();
			months.put("jan", new Integer(0));
			months.put("feb", new Integer(1));
			months.put("mar", new Integer(2));
			months.put("apr", new Integer(3));
			months.put("may", new Integer(4));
			months.put("jun", new Integer(5));
			months.put("jul", new Integer(6));
			months.put("aug", new Integer(7));
			months.put("sep", new Integer(8));
			months.put("oct", new Integer(9));
			months.put("nov", new Integer(10));
			months.put("dec", new Integer(11));
		}
		return ((Integer) months.get(month.toLowerCase())).intValue();
	}

	public static void writeXML(Document document, String filename)
			throws IOException {

		// lets write to a file

		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("GBK");
		/**
		 * Cannot write file on App Engine
		 */
		// XMLWriter writer = new XMLWriter(new PrintWriter(new FileWriter(
		// filename)), format);
		// writer.write(document);
		// writer.close();
	}

	public static void PrintXMThread(Element root, LThread lt) {
		if (root == null || lt == null || lt.notices.size() == 0)
			return;
		final String pattern = ".*?合集.*?";
		Element troot = root.addElement("thread");
		Notice n = (Notice) (lt.notices.get(0));
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < n.getResourceUrl().size(); i++) {
			sb.append((String) n.getResourceUrl().get(i));
			sb.append("\r\n");
		}
		troot.addElement("source_site").addText(n.getSourceUrl());
		troot.addElement("writer").addText(n.getWriter());
		troot.addElement("title").addText(n.getTitle());
		troot.addElement("board").addText(n.getBoard());
		troot.addElement("site").addText(n.getSite());
		troot.addElement("date").addText(n.getCalDate().getTime().toString());
		if (!n.getTitle().matches(pattern)) {
			troot.addElement("content").addText(n.getContent());
		} else {
			troot.addElement("content");
		}
		troot.addElement("resource_url").addText(sb.toString());
	}

	public static void PrintThread(LThread lt) {
		PrintStream pw = System.out;
		final String pattern = ".*?合集.*?";
		String text;
		if (lt != null && lt.notices.size() != 0) {
			Notice n = (Notice) (lt.notices.get(0));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < n.getResourceUrl().size(); i++) {
				sb.append((String) n.getResourceUrl().get(i));
				sb.append("\r\n");
			}
			if (!n.getTitle().matches(pattern)) {

				text = "\r\n" + "Source_site:" + n.getSourceUrl()
						+ "\r\nWriter:" + n.getWriter() + "\r\nTitle:"
						+ n.getTitle() + "\r\nboard:" + n.getBoard()
						+ "\r\nsite:" + n.getSite() + "\r\ndate:"
						+ n.getCalDate().getTime() + "\r\nContent:\r\n"
						+ n.getContent() + "\r\nresource_url:\r\n" + sb;
				pw.println(text);
				logger.info(text);
			} else {
				text = "\r\n" + "Source_site:" + n.getSourceUrl()
						+ "\r\nWriter:" + n.getWriter() + "\r\nTitle:"
						+ n.getTitle() + "\r\nboard:" + n.getBoard()
						+ "\r\nsite:" + n.getSite() + "\r\ndate:"
						+ n.getCalDate().getTime() + "\r\nresource_url:\r\n"
						+ sb;
				pw.println(text);
				logger.info(text);
			}
			text = ("*****************************************************");
			pw.println(text);
			logger.info(text);
		}
	}

	// public static void PrintHTMLThread(PrintWriter pw, LThread lt) {
	// // logger.info("print thread");
	// final String pattern = ".*?合集.*?";
	// if (lt != null && lt.notices.size() != 0) {
	// Notice n = (Notice) (lt.notices.get(0));
	// StringBuffer sb = new StringBuffer();
	// for (int i = 0; i < n.resource_url.size(); i++) {
	// sb.append((String) n.resource_url.get(i));
	// sb.append("<br>\r\n");
	// }
	// if (!n.title.matches(pattern)) {
	// pw.println("<br>\r\n" + "Source_site:" + n.source_url
	// + "<br>\r\nWriter:" + n.writer + "<br>\r\nTitle:"
	// + n.title + "<br>\r\nboard:" + n.board
	// + "<br>\r\nsite:" + n.site + "<br>\r\ndate:"
	// + n.date.getTime() + "<br>\r\nContent:<br>\r\n"
	// + n.content + "<br>\r\nresource_url:<br>\r\n" + sb
	// + "<br>");
	// } else {
	// pw.println("<br>\r\n" + "Source_site:" + n.source_url
	// + "<br>\r\nWriter:" + n.writer + "<br>\r\nTitle:"
	// + n.title + "<br>\r\nboard:" + n.board
	// + "<br>\r\nsite:" + n.site + "<br>\r\ndate:"
	// + n.date.getTime() + "<br>\r\nresource_url:<br>\r\n"
	// + sb + "<br>");
	// }
	// pw
	// .println("*****************************************************<br>");
	// }
	// }

	public static void PrintThread(PrintWriter pw, LThread lt) {
		// logger.info("print thread");
		final String pattern = ".*?合集.*?";
		if (lt != null && lt.notices.size() != 0) {
			Notice n = (Notice) (lt.notices.get(0));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < n.getResourceUrl().size(); i++) {
				sb.append((String) n.getResourceUrl().get(i));
				sb.append("\r\n");
			}
			if (!n.getTitle().matches(pattern)) {
				pw.println("\r\n" + "Source_site:" + n.getSourceUrl()
						+ "\r\nWriter:" + n.getWriter() + "\r\nTitle:"
						+ n.getTitle() + "\r\nboard:" + n.getBoard()
						+ "\r\nsite:" + n.getSite() + "\r\ndate:"
						+ n.getCalDate().getTime() + "\r\nContent:\r\n"
						+ n.getContent() + "\r\nresource_url:\r\n" + sb);
			} else {
				pw.println("\r\n" + "Source_site:" + n.getSourceUrl()
						+ "\r\nWriter:" + n.getWriter() + "\r\nTitle:"
						+ n.getTitle() + "\r\nboard:" + n.getBoard()
						+ "\r\nsite:" + n.getSite() + "\r\ndate:"
						+ n.getCalDate().getTime() + "\r\nresource_url:\r\n"
						+ sb);
			}
			pw.println("*****************************************************");
		}
	}

	public static Vector GetURLS(String text) {
		Pattern p = Pattern
				.compile("([Hh][Tt][Tt][Pp]:\\/\\/[\\S]+?\\.\\w{1,4})(?=(\\/(?=\\s|\\z))|[）】\\s<>'\"]|\\z)");
		Matcher m = p.matcher(text);
		Vector urls = new Vector();
		while (m.find()) {
			urls.add(m.group(1));
		}
		return urls;
	}

	public static boolean IsPicture(String url) {
		Pattern p = Pattern.compile("(.*?\\.[\\w]{3}$)");
		Matcher m = p.matcher(url);
		if (m.find())
			return true;
		return false;
	}

	public static String RemoveHTMLTag(String text) {
		// logger.info("remove html tags");
		// return text;
		// return text.replaceAll("<(.*?'*.?')*?.*?>","");
		// Pattern p=Pattern.compile("('.*?')");
		// Matcher m=p.matcher(text);
		// while(m.find())
		// {
		// text=text.replaceAll(m.group(1),"");
		// }
		// text=text.replaceAll("('.*?')","");
		// Pattern p=Pattern.compile("(<(\\w+).*?>)(?:(?s).*?)(<\\/\\2>)");
		// Matcher m=p.matcher(text);
		// while(m.find())
		// {
		// text=text.replaceAll(m.group(1),"");
		// text=text.replaceAll(m.group(3),"");
		// }
		// return text;

		// logger.info("remove html tags");
		StringReader fis = null;
		StringBuffer sb = new StringBuffer();
		try {
			try {
				fis = new StringReader(text);
				HTMLParser parser = new HTMLParser(fis);
				LineNumberReader reader = new LineNumberReader(parser
						.getReader());
				for (String l = reader.readLine(); l != null; l = reader
						.readLine()) {
					sb.append(l + "\r\n");
					// sb.append(l);
					// System.out.println(l);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} finally {
			if (fis != null)
				fis.close();
		}
		// logger.info("after removing html tags:\n" + sb.toString());
		return sb.toString();
	}

	public static String RemoveColorTag(String text) {
		return text.replaceAll("\\[[\\d;\\[]*?m", "");
	}

	/**
	 * 返回日期
	 * 
	 * @param date_text
	 *            形式例如2006年06月09日13:14:38的时间字符串
	 * @return
	 */
	public static Calendar GetCalendar(String date_text) {
		Calendar calendar = Calendar.getInstance();
		int year = (Integer.parseInt(date_text.substring(0, 4)));
		int month = (Integer.parseInt(date_text.substring(5, 7))) - 1;
		int date = (Integer.parseInt(date_text.substring(8, 10)));
		int hour = (Integer.parseInt(date_text.substring(11, 13)));
		int min = (Integer.parseInt(date_text.substring(14, 16)));
		int sec = (Integer.parseInt(date_text.substring(17, 19)));
		calendar.set(year, month, date, hour, min, sec);
		return calendar;
	}

	public static InputStream GetURLStream(String url_text) {
		try {
			URL url = new URL(url_text);
			// logger.info("Connect to " + url_text);
			return url.openStream();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// logger.info("Connect failed to " + url_text);
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		}
		return null;
	}

	public static URLConnection GetURLConnection(String url_text,
			int connect_times) {
		URLConnection c = null;
		for (int i = 0; i < connect_times; i++) {
			logger.info("Get URLConnection to " + url_text + " ");
			c = GetURLConnection(url_text);
			if (c != null) {
				logger.info("Success");
				break;
			} else {
				logger.info("Fail");
			}
		}
		if (c == null) {
			logger.info("All attemps of getting URLConnection to " + url_text
					+ " Fail");
		}
		return c;
	}

	private static URLConnection GetURLConnection(String url_text) {
		try {
			if (url_text != null) {
				URL u = new URL(url_text);
				return u.openConnection();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		}
		return null;
	}

	public static String GetURLText(String url_text, int connect_times) {
		try {
			if (url_text == null)
				return null;
			InputStream is = null;
			for (int i = 0; i < connect_times; i++) {
				// LTray.DisplayMessage("","Connect to "+url_text);
				logger.info("Connect to " + url_text + " ");
				is = GetURLStream(url_text);
				if (is != null) {
					logger.info("Success");
					break;
				} else {
					logger.info("Fail");
				}
			}
			if (is == null) {
				logger.info("All attemps of connecting to " + url_text
						+ " Fail");
				return null;
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(is,
					"GBK"));
			String line;
			StringBuffer sb = new StringBuffer();
			while ((line = in.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			in.close();
			// logger.info(sb.toString());
			return sb.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		}
		return null;
	}

	public static int GetMinIndex(String text, Vector strings, int index) {
		int min_index = Integer.MAX_VALUE;
		int current_index;
		for (int i = 0; i < strings.size(); i++) {
			current_index = text.indexOf((String) strings.get(i), index);
			if (current_index >= index && current_index < min_index) {
				min_index = current_index;
			}
		}
		if (min_index == Integer.MAX_VALUE)
			return -1;
		return min_index;
	}

	public static int GetAfterMinIndex(String text, Vector strings, int index) {
		int min_index = Integer.MAX_VALUE;
		int current_index;
		int min_length = 0;
		for (int i = 0; i < strings.size(); i++) {
			current_index = text.indexOf((String) strings.get(i), index);
			if (current_index >= index && current_index < min_index) {
				min_index = current_index;
				min_length = ((String) strings.get(i)).length();
			} else if (current_index == min_index) {
				int current_length = ((String) strings.get(i)).length();
				if (current_length > min_length) {
					min_length = current_length;
				}
			}
		}
		if (min_index == Integer.MAX_VALUE)
			return -1;
		return min_index + min_length;
	}

	public static String EncodeUrl(String url) {
		return url.replaceAll("\\&", "%26").replaceAll(" ", "%20");
	}

	private Utility() {

	}

	// private static Logger logger = Logger.getLogger(Utility.class);
	private static final Logger logger = Logger.getLogger(Utility.class
			.getName());
}
